登录 白背景

leetcode/其他/剑指 Offer II 069. 山峰数组的顶部.md

https://leetcode-cn.com/problems/B1IidL/

func peakIndexInMountainArray(arr []int) int {
    posLeft := 1
    posRight := len(arr) - 2
    var posMid int
    for {
        //返回点
        if posLeft == posRight || abs(posLeft - posRight) == 1 {
            if arr[posLeft] > arr[posRight] {
                return posLeft
            }
            return posRight
        }
        //看中点单调性
        posMid = (posRight - posLeft) >> 1 + posLeft
        if arr[posMid - 1] > arr[posMid] {
            //取左边
            posRight = posMid - 1
            continue
        }
        if arr[posMid + 1] > arr[posMid] {
            //取右边
            posLeft = posMid + 1
            continue
        }
        return posMid
    }
    return 0
}
func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}